<?php

require_once 'Mage/Catalog/controllers/ProductController.php';

class Mageex_AjaxCart_ProductController extends Mage_Catalog_ProductController
{
    public function viewAction()
    {
        if (!$product = $this->_initProduct()) {
         
            return $this->_sendJson(array(
               'message' => trim('Product not found', "\n\t ")
            ));
        }

        Mage::dispatchEvent('catalog_controller_product_view', array('product'=>$product));

        Mage::getSingleton('catalog/session')->setLastViewedProductId($product->getId());
        Mage::getModel('catalog/design')->applyDesign($product, Mage_Catalog_Model_Design::APPLY_FOR_PRODUCT);

//        $this->_initProductLayout($product);
        Mage::helper('catalog/product_view')->initProductLayout($product, $this);
       // $this->initLayoutMessages(array(
           // 'catalog/session', 'tag/session', 'checkout/session'));

        $content = $this->getLayout()->getBlock('product.info')->toHtml();

        // move local js variable to global scope
        $varscripts = array(
            'optionsPrice',
            'spConfig',
            'optionFileUpload',
            'optionTextCounter',
            'opConfig',
            'DateOption',
            'productAddToCartForm',
            'addTagFormJs',
            'bundle'
        );
        foreach ($varscripts as $varscript) {
            $content = str_replace('var ' . $varscript, $varscript, $content);
        }
	//validateOptionsCallback to global js scope 
	$content = str_replace('function validateOptionsCallback(elmId, result){', 
            'window.validateOptionsCallback = function (elmId, result){', 
            $content
        );
        
	//fix configurable trabl (remove from form url bad suffix)
        $content = str_replace('?___SID=U', '', $content);

        // Replace current url with the url of the page where QuickShopping window was called
        // this is done for correct work of 'Continue Shopping', 'Add tag' buttons, etc.
        $currentEncodedUrl = substr(Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl()), 0, -1);
        $refererEncodedUrl = $this->getRequest()->getParam(
            Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED,
            Mage::getBaseUrl()
        );
        $content = str_replace(
            $currentEncodedUrl,
            $refererEncodedUrl . '/',
            $content
        );

        $this->_sendJson(array(
            'productView' => trim($content, "\n\t ")
        ));
    }

    private function _sendJson(array $data = array())
    {
        // clear message stack
        $storageAreas[] = Mage::getSingleton('checkout/session');
        $storageAreas[] = Mage::getSingleton('catalog/session');
        foreach ($storageAreas as $storage){
            $storage->getMessages(true);
        }

        @header('Content-type: application/json');
        echo json_encode($data);
        exit();
    }
}
